var questionnaireFormValidator;

$(document).ready(function () {
    $.validator.setDefaults({
        errorClass: "uk-text-danger",
        errorPlacement: function (error, element) {
            error.insertAfter(element.parent("div"));
        },
        highlight: function (element, errorClass, validClass) {
            $(element).addClass("uk-form-danger");
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).removeClass("uk-form-danger");
        }
    });

    $("#btn_submit").click(function () {
        if($("input[type=radio]:checked").length == $("input[type=radio]").length/4)
            UIkit.modal.confirm("确定提交问题？", onQuestionnaireSubmit);
        else
            alert("尚有问题未做出选择，请重新检查一次问卷！！！");
    });
});

function objectToString(o, defaultVal) {
    if (defaultVal == null)
        defaultVal = "";
    return o == null ? defaultVal : o.toString();
}

var blockingModal;
function onQuestionnaireSubmit() {
    var form = $('#form_questionnaire');
    var trs = document.getElementsByTagName('tr'),
        len = (trs.length-1)/2,count = 0;
    //alert(len);
    for(var i = 0; i < len; i++){
        // var inputs = document.getElementsByName('score+'+(i+1))
        // count+=inputs.value;
        count+=$("input[type=radio]:checked")[i].value-'0';
    }
    //alert(count);
    data = {count:count,comment:$('#comment')[0].value};
    blockingModal = UIkit.modal.blockUI("正在提交...");
    $.ajax({
        url: '/api/student/do_review',
        data: JSON.stringify(data),
        method: 'POST',
        contentType: 'application/json'
    })
        .done(function () {
            blockingModal.hide();
            UIkit.modal.blockUI("提交成功！3 秒后将刷新页面。");
            setTimeout(function (args) { window.location.reload(true) }, 3000);
        })
        .fail(function (jqXHR) {
            try {
                var response = JSON.parse(jqXHR.responseText);
                if (response != null && response.error != null) {
                    UIkit.modal.alert("Error: " + response.error.message);
                } else {
                    UIkit.modal.alert("Error occurred.")
                }
            } catch (e) {
                UIkit.modal.alert("Error occurred.");
                console.error(e);
            } finally {
                blockingModal.hide();
            }
        })
}